package com.example.im;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.model.User;
import com.example.util.BaseActivity;
import com.example.util.KeyboardsUtils;
import com.example.util.MyUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;

import static com.example.db.CommonData.commonData;
import static com.example.db.CommonData.getDbUser;
import static com.example.util.MyUtil.myUtil;
import static com.example.util.MyUtil.toast;

public class LoginActivity extends BaseActivity {
    private TextView name;
    private TextView password;
    private Button login;
    private Button request;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        name = findViewById(R.id.username);
        password = findViewById(R.id.password);
        login = findViewById(R.id.login);
        request = findViewById(R.id.request);


        ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    /***
                     * 被调Activity一旦返回值,该回调方法将被系统自动调用
                     */
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        //如果返回的结果码为Activity.RESULT_OK
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            //从result中获得intent，并得到intent中的数据
                            Intent intent = result.getData();
                            assert intent != null;
                            Bundle data = intent.getExtras();
                            assert data != null;
                            boolean isRequest = data.getBoolean("isRequest");
                            //如果注册成功，修改用户名和密码为注册信息
                            if (isRequest) {
                                User user = (User) data.getSerializable("user");
                                assert user != null;
                                name.setText(user.getName());
                                password.setText(user.getPassword());
                            }
                        }
                    }
                });

        initLoginButtonEvent();
        request.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RequestActivity.class);
            launcher.launch(intent);
        });
    }

    private void initLoginButtonEvent() {
        login.setOnClickListener(v -> {
            String userName = name.getText().toString();
            String pwd = password.getText().toString();

            //调用接口，判断用户是否存在
            MyUtil.exeTask(() -> {
                Map<String, String> param = new HashMap<>();
                param.put("account", userName);
                param.put("password", pwd);
                MyUtil.Res res = MyUtil.postReqParam("/user/login", param);

                login.post(() -> {
                    if (res != null) {
                        try {
                            //登录成功
                            if (res.getCode() == 200) {
                                //如果存在跳转主页面并提示登录成功

                                //跳转主页面
                                User loginUser = new User();
                                JSONObject d = res.getDataObject();
                                loginUser.setId(d.getInteger("id"));
                                loginUser.setName(d.getString("username"));
                                loginUser.setLoginIp(d.getString("loginIp"));
                                //调用接口获取所有用户信息
                                //将当前用户信息存入数据中
                                commonData.setToken(d.getString("accessToken"));
                                //将获取的好友信息和消息信息存入commondata中
                                commonData.setLogin(true);
                                commonData.setUser(loginUser);
                                //启动对应的Activity
                                toast(LoginActivity.this, "登录成功");
//                                toast(LoginActivity.this, res.getMessage());
                                MyUtil.changeActivity(LoginActivity.this,MainActivity.class,true);

                            } else {
                                toast(LoginActivity.this, res.getMessage());
                            }
                        } catch (Exception exception) {
                            exception.printStackTrace();
                            toast(LoginActivity.this, "异常：" + exception.getMessage());
                        }
                    }else {
                        toast(LoginActivity.this, "网络异常");
                    }

                });
            });


        });
    }

    private User getLoginUser(String userName, String pwd) {
        User dbUser = getDbUser(userName);
        if (dbUser != null && Objects.equals(dbUser.getPassword(), pwd)) {
            return dbUser;
        }
        return null;
    }

    /**
     * 点击非编辑区域收起键盘
     * 获取点击事件
     */
    @CallSuper
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (KeyboardsUtils.isShouldHideKeyBord(view, ev)) {
                KeyboardsUtils.hintKeyBoards(view);
            }
        }
        return super.dispatchTouchEvent(ev);
    }
}
